//
//  BIDLoginViewController.m
//  EducationAssistant
//
//  Created by mal on 15/6/2.
//  Copyright (c) 2015年 cnsoft. All rights reserved.
//

#import "BIDLoginViewController.h"
#import "BIDGlobalMethods.h"
#import "BIDMainViewController.h"
#import "UIView+FindFirstResponder.h"
#import "BIDDatabaseManager.h"
#import "BIDCustomTextField.h"

//登录
static NSString *loginURL = @"userAndroid!login.action";

@interface BIDLoginViewController ()
{
    UIImageView *_imgViewForAccount;
    UIImageView *_imgViewForPwd;
}

@end

@implementation BIDLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.view setBackgroundColor:RGBACOLOR(230, 230, 237.f, 1.f)];
    _imgView.clipsToBounds = YES;
    _imgView.layer.cornerRadius = 5.f;
    _containerView.clipsToBounds = YES;
    _containerView.layer.cornerRadius = 5.f;
    [self initLayout];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *初始化界面
 */
- (void)initLayout
{
    self.navigationController.navigationBarHidden = YES;
    //
    _usernameTF.inputAccessoryView = self.toolBar;
    _passwordTF.inputAccessoryView = self.toolBar;
    //设置按钮背景
    [BIDGlobalMethods setImgForBtn:_loginBtn imgNameForNormal:@"loginBtnBg_normal.png" imgNameForHighlight:@"loginBtnBg_select.png"];
    //add tapGesture for view
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandler:)];
    tapGR.numberOfTapsRequired = 1;
    tapGR.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tapGR];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    //填充用户名
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *strUsername = [userDefaults objectForKey:@"username"];
    if(strUsername.length>0)
    {
        _usernameTF.text = strUsername;
    }
}

- (IBAction)textFieldEditBeginHandler:(id)sender
{
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.keyboardHeight = keyboardSize.height;
    
    //NSValue *durationValue = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView *firstResponderView = [keyWindow findFirstResponder];
    
    CGFloat containerViewY = CGRectGetMinY(_containerView.frame);
    
    if(firstResponderView.frame.origin.y + firstResponderView.frame.size.height + containerViewY > (self.view.frame.size.height-(self.keyboardHeight-self.distanceToMove)))
    {
        //NSTimeInterval timeInterval;
        //[durationValue getValue:&timeInterval];
        [UIView beginAnimations:@"animation" context:nil];
        [UIView setAnimationDuration:0.25f];
        CGRect frame = self.view.frame;
        
        int moveLen = containerViewY + firstResponderView.frame.origin.y + firstResponderView.frame.size.height - (self.view.frame.size.height-(self.keyboardHeight-self.distanceToMove));
        self.distanceToMove += moveLen;
        frame.origin.y -= moveLen;
        self.view.frame = frame;
        [UIView commitAnimations];
    }
}

/**
 *登录
 */
- (IBAction)loginBtnHandler:(id)sender
{
    NSString *strUsername = _usernameTF.text;
    NSString *strPassword = _passwordTF.text;
    if(strUsername.length==0 || strPassword.length==0)
    {
        //用户名和密码不能为空
        [BIDGlobalMethods showAlertView:@"用户名和密码不能为空" buttonTitle:@"关闭" delegate:nil tag:0];
        return;
    }
    //先登录本平台
    [self loginOwnPlatformWithUsername:strUsername password:strPassword];
}
/**
 *登录本平台,isDynamic表示是否使用的动态获取的体验账号登录的
 */
- (void)loginOwnPlatformWithUsername:(NSString*)strUsername password:(NSString*)strPassword
{
    NSString *strURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], loginURL];
    NSString *strPost = @"";
//    获取设备唯一标识符
    NSString *strIDFV = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    strPost = [[NSString alloc] initWithFormat:@"userName=%@&password=%@&mobileCode=%@", strUsername, strPassword, strIDFV];
//    strPost = [[NSString alloc] initWithFormat:@"userName=%@&password=%@", strUsername, strPassword];
    BIDDataCommunication *dc = [[BIDDataCommunication alloc] init];
    [self showSpinnerView];
    [dc getDataFromNet:strURL postValue:strPost completionHandler:^(id obj, NSError *err){
        [self hideSpinnerView];
        if(obj && !err)
        {
            if([obj isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *responseDic = (NSDictionary*)obj;
                NSNumber *resValue = responseDic[@"isSuccess"];
                if([resValue integerValue] == 1)
                {
                    //登录成功，保存用户名和密码
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:strUsername forKey:@"username"];
                    [userDefaults setObject:strPassword forKey:@"password"];
                    [userDefaults synchronize];
                    //
                    NSDictionary *subDic = responseDic[@"info"];
                    //保存userId
                    NSString *strUserId = subDic[@"id"];
                    [AppDelegate setUserId:strUserId];
                    [AppDelegate setUserTrueName:subDic[@"trueName"]];
                    [AppDelegate setUserName:subDic[@"userName"]];
                    [AppDelegate setUserDepartmentId:subDic[@"departmentid"]];
                    //
                    BIDMainViewController *vc = [[BIDMainViewController alloc] init];
                    [self.navigationController setViewControllers:@[vc]];
                }
                else
                {
                    [self showAlertView:responseDic[@"msg"] buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                }
            }
        }
        else
        {
            if(err)
            {
                [BIDGlobalMethods showAlertView:[err localizedDescription] buttonTitle:@"关闭" delegate:nil tag:0];
            }
            else
            {
                [BIDGlobalMethods showAlertView:@"登录失败" buttonTitle:ALERT_BTN_TITLE delegate:nil tag:0];
            }
        }
    }];
}

/**
 *
 */
- (void)tapGestureHandler:(UIGestureRecognizer*)gr
{
    [_usernameTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
}
/**
 *
 */
- (IBAction)textFieldEditDone:(id)sender
{
    [_usernameTF resignFirstResponder];
    [_passwordTF resignFirstResponder];
}
@end
